<template>
  <el-card shadow="always" style="margin-bottom: 10px">
    <CategorySelector :isDisabled="!isShowAttrList"></CategorySelector>
  </el-card>
  <el-card shadow="always">
    <!-- 显示平台属性队形的表格 -->
    <div v-if="isShowAttrList">
      <el-button v-has="'btn.Attr.add'" title="添加属性" type="primary" :icon="Plus" @click="showAdd" :disabled="!CategoryStore.getCategory3Id">添加属性</el-button>
      <el-table row-key="id" :data="attrList" stripe border style="width: 100%" v-loading="loading">
        <!-- 序号列 -->
        <el-table-column align="center" type="index" label="序号" width="80" />
        <!-- 属性名称列 -->
        <el-table-column prop="attrName" label="属性名称" />
        <!-- 属性值列表 -->
        <el-table-column prop="attrValueList" label="属性值列表">
          <template #default="{ row }">
            <el-tag class="ml-2" type="success" v-for="val in row.attrValueList" :key="val.id">{{ val.valueName }}</el-tag>
          </template>
        </el-table-column>
        <!-- 修改删除列 -->
        <el-table-column label="操作">
          <template #default="{ row, $index }">
            <el-tooltip class="box-item" effect="dark" content="修改" placement="top">
              <el-button size="default" :icon="Edit" type="primary" @click="showUpdate(row)"></el-button>
            </el-tooltip>

            <el-popconfirm :title="`您确定要删除 ${row.attrName} 吗？`" @confirm="deleteAttr(row)">
              <template #reference> <el-button size="default" :icon="Delete" type="danger"></el-button>> </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 显示修改或者添加的页面 -->
    <div v-else>
      <!-- 显示平台属性对象属性名 -->
      <el-form inline>
        <el-form-item label="属性名">
          <el-input type="text" v-model="attr.attrName">xxx</el-input>
        </el-form-item>
      </el-form>
      <!-- 两个按钮 -->
      <div>
        <el-button type="primary" size="default" icon="Plus" @click="addAttrValue" :disabled="!attr.attrName">添加属性</el-button>
        <el-button size="default" @click="isShowAttrList = true">取消</el-button>
      </div>
      <!-- 表格 -->
      <el-table row-key="id" :data="attr.attrValueList" stripe border style="width: 100%">
        <!-- 序号列 -->
        <el-table-column align="center" type="index" label="序号" width="80" />
        <!-- 属性值称列 -->
        <el-table-column prop="valueName" label="属性值名称">
          <template #default="{ row, $index }">
            <el-input :ref="(input:any)=>inputRef[$index] = input" v-if="row.isShowEdit" type="text" size="small" @blur="showSpan(row, $index)" v-model="row.valueName"></el-input>
            <span v-else style="display: inline-block; width: 100%" @click="showInput(row, $index)">{{ row.valueName }}</span>
          </template>
        </el-table-column>
        <!-- 修改删除列 -->
        <el-table-column label="操作">
          <template #default="{ row, $index }">
            <el-popconfirm :title="`您确定要删除 ${row.valueName} 吗？`" @confirm="attr.attrValueList.splice($index, 1)">
              <template #reference>
                <el-button size="default" :icon="Delete" type="danger"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 又是两个按钮 -->
      <div>
        <el-button type="primary" @click="saveAttrValue" :disabled="!attr.attrName || !attr.attrValueList.length">保存</el-button>
        <el-button size="default" @click="isShowAttrList = true">取消</el-button>
      </div>
    </div>
  </el-card>
</template>
<script lang="ts">
export default {
  name: "Attr",
};
</script>
<script lang="ts" setup>
import CategorySelector from "../../../components/CategorySelector/index.vue";
import useCategoryStore from "../../../stores/category";
import { onBeforeUnmount, ref, watch, reactive, nextTick } from "vue";
// 引入平台属性对象数组需要的类型
import type { AttrListModel, AttrModel, AttrValueListModel, AttrValueModel } from "../../../api/product/model/attrModel";
// 引入按钮的icon
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
// 引入获取attrLIst的接口函数
import { reqAddOrUpdateAttr, reqDeleteAttrById, reqGetAttrList } from "../../../api/product/attr";
// 引入深拷贝的方法
import cloneDeep from "lodash/cloneDeep";
import { ElMessage } from "element-plus";
// 加载的效果的标识
const loading = ref<boolean>(false);
// 获取仓库的对象
const CategoryStore = useCategoryStore();

// 定义attr的数组
const attrList = ref<AttrListModel>([]);

const getAttrList = async () => {
  attrList.value = await reqGetAttrList({
    category1Id: CategoryStore.getCategory1Id as number,
    category2Id: CategoryStore.getCategory2Id as number,
    category3Id: CategoryStore.getCategory3Id as number,
  });
};

watch(
  () => CategoryStore.getCategory3Id,
  (category3Id) => {
    if (!category3Id) {
      attrList.value = [];
      return;
    }

    getAttrList();
  }
);

onBeforeUnmount(() => {
  CategoryStore.$state = {
    category1Id: undefined, //一级分类的id
    category2Id: undefined, //二级分类的id
    category3Id: undefined, //三级分类的id
    category1List: [], //一级分类的列表数据
    category2List: [], //二级分类的列表数据
    category3List: [], //三级分类的列表数据
  };
});

// 定义一个切换添加与修改的页面的标识符
const isShowAttrList = ref<boolean>(true);
// 定义添加属性的点击事件
const showAdd = () => {
  Object.assign(attr, {
    attrName: "",
    attrValueList: [],
    categoryId: CategoryStore.getCategory3Id as number,
    categoryLevel: 3,
  });
  isShowAttrList.value = false;
};
const showUpdate = (row: AttrModel) => {
  // 浅拷贝
  // Object.assign(attr, row);
  // 深拷贝
  Object.assign(attr, cloneDeep(row));
  isShowAttrList.value = false;
};

// 定义平台属性的对象数组
const attr = reactive<AttrModel>({
  attrName: "",
  attrValueList: [],
  categoryId: -1,
  categoryLevel: 3,
});

// 定义一个input编辑的数组inputs
const inputRef = ref<HTMLInputElement[]>([]);

// 编辑模式
const showInput = (row: AttrValueModel, index: number) => {
  row.isShowEdit = true;
  nextTick(() => {
    inputRef.value[index].focus();
  });
};

//   查看模式
const showSpan = (row: AttrValueModel, index: number) => {
  if (!row.valueName) {
    attr.attrValueList.splice(index, 1);
    return;
  }
  row.isShowEdit = false;
};

//点击添加属性的回调
const addAttrValue = () => {
  attr.attrValueList.push({
    attrId: attr.id as number,
    valueName: "",
    isShowEdit: true,
  });
  nextTick(() => {
    inputRef.value[attr.attrValueList.length - 1].focus();
  });
};

// 点击保存的回调
const saveAttrValue = async () => {
  // 把新的三级分类的id重新的更新到attr的categoryId
  attr.categoryId = CategoryStore.getCategory3Id as number;
  // 新添加的数据中多了一个isShowEdit  是不要的  而且 有的数据是空格  也是不要的
  attr.attrValueList = attr.attrValueList.filter((attrValue) => {
    if (attrValue.valueName.trim() === "") {
      return false;
    } else {
      delete attrValue.isShowEdit;
      return true;
    }
  });

  // 调用接口  ，先移入接口
  try {
    await reqAddOrUpdateAttr(attr);
    isShowAttrList.value = true;
    ElMessage.success("保存成功");
    getAttrList();
  } catch (error) {
    ElMessage.error("保存失败");
  }
};

// 点击删除按钮的回调函数
const deleteAttr = async (row: AttrModel) => {
  try {
    await reqDeleteAttrById(row.id as number);
    ElMessage.success("删除成功");
    getAttrList();
  } catch (error) {
    ElMessage.error("删除失败");
  }
};
</script>
<style scoped></style>
